<template>
  <div class="interface-info">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="接口名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入接口名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="接口状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="在线" :value="1" />
            <el-option label="离线" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>接口列表</span>
          <el-button type="primary" @click="handleAdd">新增接口</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="接口名称" min-width="150" />
        <el-table-column prop="description" label="接口描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="url" label="接口地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag :type="getMethodTagType(row.method)">{{ row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              v-if="row.status === 0"
              type="success"
              size="small"
              @click="handleOnline(row)"
            >
              发布
            </el-button>
            <el-button
              v-else
              type="warning"
              size="small"
              @click="handleOffline(row)"
            >
              下线
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入接口描述"
          />
        </el-form-item>
        <el-form-item label="接口地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入接口地址" />
        </el-form-item>
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="form.method" placeholder="请选择请求方法" style="width: 100%">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求参数" prop="requestParams">
          <el-input
            v-model="form.requestParams"
            type="textarea"
            :rows="4"
            placeholder="请输入请求参数（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="请求头" prop="requestHeader">
          <el-input
            v-model="form.requestHeader"
            type="textarea"
            :rows="4"
            placeholder="请输入请求头（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="响应头" prop="responseHeader">
          <el-input
            v-model="form.responseHeader"
            type="textarea"
            :rows="4"
            placeholder="请输入响应头（JSON格式）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listInterfaceInfoForAdminUsingGET,
  addInterfaceInfoUsingPOST,
  updateInterfaceInfoUsingPOST,
  deleteInterfaceInfoUsingPOST,
  onlineInterfaceInfoUsingPOST,
  offlineInterfaceInfoUsingPOST
} from '@/api/interfaceInfo'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增接口')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: '',
  url: '',
  method: '',
  requestParams: '',
  requestHeader: '',
  responseHeader: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入接口名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入接口描述', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入接口地址', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择请求方法', trigger: 'change' }
  ]
}

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const typeMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return typeMap[method] || 'info'
}

// 构建查询参数，过滤空值
const buildQueryParams = () => {
  const params = {
    current: pagination.current,
    pageSize: pagination.pageSize
  }
  
  // 只有当搜索条件不为空时才添加到参数中
  if (searchForm.name && searchForm.name.trim()) {
    params.name = searchForm.name.trim()
  }
  
  if (searchForm.status !== '' && searchForm.status !== null && searchForm.status !== undefined) {
    params.status = searchForm.status
  }
  
  return params
}

// 获取接口列表
const getInterfaceList = async () => {
  loading.value = true
  try {
    const params = buildQueryParams()
    const response = await listInterfaceInfoForAdminUsingGET(params)
    
    // 根据实际返回的数据结构处理
    if (Array.isArray(response.data)) {
      // 如果返回的是数组，直接使用
      tableData.value = response.data
      pagination.total = response.data.length
    } else if (response.data && response.data.records) {
      // 如果返回的是分页格式
      tableData.value = response.data.records
      pagination.total = response.data.total || 0
    } else {
      // 兜底处理
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取接口列表失败:', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getInterfaceList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getInterfaceList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  getInterfaceList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增接口'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑接口'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 发布
const handleOnline = async (row) => {
  try {
    await ElMessageBox.confirm('确定要发布该接口吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await onlineInterfaceInfoUsingPOST({ id: row.id })
    ElMessage.success('发布成功')
    getInterfaceList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

// 下线
const handleOffline = async (row) => {
  try {
    await ElMessageBox.confirm('确定要下线该接口吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await offlineInterfaceInfoUsingPOST({ id: row.id })
    ElMessage.success('下线成功')
    getInterfaceList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('下线失败')
    }
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该接口吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteInterfaceInfoUsingPOST({ id: row.id })
    ElMessage.success('删除成功')
    getInterfaceList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (form.id) {
      // 编辑
      await updateInterfaceInfoUsingPOST(form)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addInterfaceInfoUsingPOST(form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    getInterfaceList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: '',
    description: '',
    url: '',
    method: '',
    requestParams: '',
    requestHeader: '',
    responseHeader: ''
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  getInterfaceList()
})
</script>

<style scoped lang="scss">
.interface-info {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>